package org.example.controller;

import org.example.service.UserService;
import org.example.service.impl.UserServiceImpl;
import org.example.vo.Users;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
* @author 王学龙
 * @date 2025/6/24
 * Controller层作用，完成用户的请求，进行响应处理
 */

@WebServlet("/login.action")
public class LoginController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        System.out.println("用户登录");
        // 获取前端输入的参数
        String username = request.getParameter("username").trim();
        String password = request.getParameter("password").trim();
        UserService service = UserService.getInstance();
        Users users = new Users();
        users.setUsername(username);
        users.setPassword(password);
        users = service.userLogin(users);

        if(users == null){
//            System.out.println(users.getUsername());
            request.setAttribute("loginErr","用户名或密码不正确");
            request.getRequestDispatcher("./login.jsp").forward(request, response);
        }else {
            HttpSession session = request.getSession();
            session.setAttribute("userInfo",users);
            response.sendRedirect("main.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
